<template>
  <div class="dict">
    <ele-left-right-master-sub-two-table
      ref="table"
      :masterColumn="masterColumn"
      :subColumn="subColumn"
      :sub2Column="sub2Column"
      :formConfig="formConfig"
      :operateList="operateList"
      :subOperateList="operateList"
      :sub2OperateList="operateList"
      :masterApi="gradeListOne"
      height="700"
      :subApi="gradeListTwo"
      :sub2Api="typeOrderRepairPage"
      @handleOperateEvent="handleMasterOperateEvent"
      @handleSubOperateEvent="handleSubOperateEvent"
      @handleSub2OperateEvent="handleSub2OperateEvent"
      :subRequestParams="subRequestParams"
      :sub2RequestParams="sub2RequestParams"
      @row-click="handleClick"
      @dataFlushed="onDataFlushed($event)"
    />
    <ele-form-drawer
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="formDescDialog"
      :request-fn="handleSubmit"
      :visible.sync="visible"
      :title="title"
    >
    </ele-form-drawer>
    <ele-form-drawer
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="formDescDialogSub"
      :request-fn="handleSubmitSub"
      :visible.sync="visibleSub"
      :title="title"
    >
    </ele-form-drawer>
    <ele-form-drawer
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="formConfigDialog"
      :request-fn="handleSubmit"
      :visible.sync="visibleConfig"
      :title="title"
    >
    </ele-form-drawer>
    <ele-dialog-table
      title="维修项目关联"
      width="800px"
      :visible.sync="mixinDialogVisible"
      :formConfig="mixinSearchDialog"
      :column="mixinDialogColumn"
      @getSelectData="getSelectMixin"
      :getList="getMixinList"
      :hasFooter="hasMixinFooter"
    ></ele-dialog-table>
  </div>
</template>
<script>
import {
  operateList,
  formConfig,
  rowConfig,
  subRowConfig,
  formDescDialog,
  formDescDialogSub,
  formConfigDialog,sub2RowConfig
} from './config'
import {
  typeOrderCreate,
  typeOrderUpdate,
  typeOrderPage,
  typeOrderDeleteById,
  gradeListOne,
  gradeListTwo,typeOrderRepairCreate, typeOrderRepairDeleteById,typeOrderRepairPage
} from '@/api/pickUpCar/orderType'
import {repairItemPage as getMixinList} from "@/api/repair/item";
import {getDict} from "@/api/common";
export default {
  name: 'orderType',
  data() {
    return {
      mixinDialogVisible: false, //表格弹框隐藏显示
      getMixinList, // 获取弹框数据接口
      hasMixinFooter: true, // 是否需要底部按钮默认true
      mixinSearchDialog: {
        inline: true,
        formDesc: {
          repairProf: {
            type: "select",
            label: '工种',
            prop: {
              text: "description",
              value: "value"
            },
            // Promise 对象
            options: async (data) => {
              const list = await getDict("work_type")
              return list.data.result
            }
          },
          repairCateFir: {
            type: "input",
            label: '一级分类',
          },
          repairCateSec: {
            type: "input",
            label: '二级分类',
          },
          repairItem: {
            type: "input",
            label: '维修项目',
          },
          isBase: {
            label: "基础整备项",
            type: "select",
            options: [
              { text: "是", value: "Y" },
              { text: "否", value: "N" }
            ]
          }
        },
      },
      mixinDialogColumn: [
        {
          type: "selection",
        },
        {
          type: "index",
          label: $i18n.t("common.order"),
          width: 60,
        },
        {
          prop: "repairProf",
          label: '工种',
          optionProp: {
            value: "value",
            label: "description",
          },
          option: async (data) => {
            const list = await getDict("work_type")
            return list.data.result;
          },
          showOverflowTooltip: true,
        },
        {
          prop: 'repairCateFir',
          label: '一级分类',
          showOverflowTooltip: true
        },
        {
          prop: 'repairCateSec',
          label: '二级分类',
          showOverflowTooltip: true
        },
        {
          prop: 'repairItem',
          label: '维修项目',
          showOverflowTooltip: true
        },
        {
          prop: 'repairHours',
          label: '工时',
          showOverflowTooltip: true
        },
        {
          prop: 'repairHoursUnitPrice',
          label: '工时单价',
          showOverflowTooltip: true
        },
        {
          prop: 'repairHoursTotalPrice',
          label: '工时总价',
          showOverflowTooltip: true
        },
        {
          prop: 'isBase',
          label: '基础整备项',
          showOverflowTooltip: true,
          render: (h, scope) => {
            const qmiTestStep = { 'Y': '是', 'N': '否' }
            return (
              <span>{qmiTestStep[scope.row.isBase] || ''}</span>
            )
          }
        },
        {
          prop: 'isRepair',
          label: '使用物料',
          showOverflowTooltip: true,
          render: (h, scope) => {
            const qmiTestStep = { 'Y': '是', 'N': '否' }
            return (
              <span>{qmiTestStep[scope.row.isRepair] || ''}</span>
            )
          }
        },
        {
          prop: 'repairMaterialName',
          label: '使用物料名称',
          showOverflowTooltip: true,
        },
      ],
      sub2RequestParams: {
        column: [{ key : 'orderTypeId' ,value: 'id' }]
      },
      sub2Column: [
        {
          prop: 'repairCateFir',
          label: '一级分类'
        },
        {
          prop: 'repairCateSec',
          label: '二级分类'
        },
        {
          prop: 'repairItem',
          label: '维修项目'
        },
        {
          prop: 'operate',
          label: this.$t('common.operation'),
          render: (h, scope) => {
            return (
              <ele-row-operation
                scope={scope}
                rowConfig={sub2RowConfig}
                onRowOperate={this.rightRow2Operate}></ele-row-operation>
            )
          }
        }
      ],
      operateList, //左侧操作按钮
      formConfig, //搜索配置
      // getAuthDict,
      typeOrderPage,
      gradeListTwo,
      gradeListOne,
      typeOrderRepairPage,
      // getAuthDictItem,
      //请求子表时的数据
      subRequestParams: {
        column: [{ value: 'type' }, { value: 'parentId' }]
      },
      masterColumn: [
        // {
        //   prop: 'component',
        //   label: this.$t('dict.component'),
        //   minWidth: 60,
        //   optionProp: {
        //     label: 'sysName',
        //     value: 'sysCode'
        //   },
        //   option: async () => {
        //     const list = await getComponentList()
        //     return list.data.result
        //   }
        // },
        // {
        //   prop: 'systemFlag',
        //   label: this.$t('dict.systemFlag'),
        //   minWidth: 40,
        //   render: (h, params) => {
        //     let dictTypeName =
        //       params.row.systemFlag == '1' ? $i18n.t('common.yes') : $i18n.t('common.no')
        //     let dictTypeStyle = params.row.systemFlag == '1' ? 'success' : 'info'
        //     return <el-tag type={dictTypeStyle}>{dictTypeName}</el-tag>
        //   }
        // },
        {
          prop: 'orderTypeName',
          label: '订单类型名称'
        },
        {
          prop: 'orderTypeCode',
          label: '订单类型编码'
        },

        {
          prop: 'operate',
          label: this.$t('common.operation'),
          width: 160,
          render: (h, scope) => {
            return (
              <ele-row-operation
                scope={scope}
                rowConfig={rowConfig}
                onRowOperate={this.leftRowOperate}></ele-row-operation>
            )
          }
        }
      ],
      subColumn: [
        {
          prop: 'orderTypeName',
          label: '分类名称'
        },
        {
          prop: 'orderTypeCode',
          label: '分类编码'
        },
        {
          prop: 'recheckDicMap',
          label: '复检项',
          render: (h, scope) => {
            let values = Object.values(scope.row.recheckDicMap)
            let temp = values.join(' ')
            return <span>{temp}</span>
          }
        },
        {
          prop: 'sequence',
          label: '排序'
        },

        {
          prop: 'operate',
          label: this.$t('common.operation'),
          render: (h, scope) => {
            return (
              <ele-row-operation
                scope={scope}
                rowConfig={subRowConfig}
                onRowOperate={this.rightRowOperate}></ele-row-operation>
            )
          }
        }
      ],
      title: '',
      isLoading: false,
      visible: false,
      visibleConfig: false,
      visibleSub: false,
      formDescDialog,
      formConfigDialog,
      formDescDialogSub,
      formDataDialog: {},
      tableChange: 'left',
      id: '',
      type: '',
      editId: '',
      repairId:'',
      typeId:''
      // systemFlag: ''
    }
  },
  created() {},
  methods: {
    onDataFlushed(value) {
      if(value.type === 'sub')
      {
        this.typeId = value.value.id
      }
      else
      {
        this.typeId = ''
      }
    },
    getSelectMixin(data) {
      let ids = ''
      const length = data.length
      data.forEach(function (item, index) {
        ids += item.id
        if (index !== length - 1) {
          ids += ','
        }
      })
      // 调试完成记得删除控制台打印
      console.log(ids);
      typeOrderRepairCreate(
        {
          repairId:ids,
          orderTypeId:this.typeId
        }
      ).then((res) => {
        this.$refs.table.sub2Refresh(true)
        this.visibleSub2 = false
      })
    },
    handleSub2OperateEvent(data) {
      if (this.typeId == '') {
        this.$message.error('未选择分类数据')
        return
      }
      this.mixinDialogVisible = true
    },
    rightRow2Operate({ handleName, row }) {
      console.warn(handleName)
      const fun = {
        deleteSub2: () => {
          this.$confirm(
            this.$t('common.deleteSingle', { name: '条数据' }),
            this.$i18n.t('common.tip'),
            {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
            .then(() => {
              typeOrderRepairDeleteById(row.id).then((res) => {
                this.$message({
                  type: 'success',
                  message: '删除成功'
                })
                this.$refs.table.sub2Refresh(true)
              })
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: this.$i18n.t('common.cancel')
              })
            })
        },
      }
      fun[handleName] && fun[handleName]()
    },
    //左边表格顶部的按钮事件
    handleMasterOperateEvent(data) {
      this.title = '新增'
      this.tableChange = 'left'
      this.formDataDialog = {}
      this.visible = true
    },
    //左边行操作事件
    leftRowOperate({ handleName, row }) {
      const fun = {
        edit: () => {
          // let systemFlag = row.systemFlag
          this.title = '编辑'
          this.tableChange = 'left'
          this.visible = true
          this.edit(row)
          // if ('0' === systemFlag) {
          //   this.title = this.$t('common.edit')
          //   this.tableChange = 'left'
          //   this.visible = true
          //   this.edit(row)
          // } else {
          //   //     系统内置的不可编辑
          //   this.$message({
          //     type: 'info',
          //     message: this.$i18n.t('dict.noEditMessage')
          //   })
          // }
        },
        config: () => {
          this.title = this.$t('dict.config')
          this.tableChange = 'left'
          this.visibleConfig = true
          this.editConfig(row)
        },
        delete: () => {
          // let systemFlag = row.systemFlag
          this.$confirm(
            "此操作将删除该数据及关联明细数据, 是否继续?",
            this.$i18n.t('common.tip'),
            {
              confirmButtonText: this.$i18n.t('common.ok'),
              cancelButtonText: this.$i18n.t('common.cancel'),
              type: 'warning'
            }
          )
            .then(() => {
              typeOrderDeleteById(row.id).then((res) => {
                this.$message({
                  type: 'success',
                  message: this.$t('common.deleteSuccess')
                })
                this.$refs.table.refresh(true)
              })
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: this.$i18n.t('common.cancel')
              })
            })
        }
      }
      fun[handleName] && fun[handleName]()
    },
    edit(data) {
      this.formDataDialog = { ...data }
      this.editId = data.id
    },
    editConfig(data) {
      this.formDataDialog = {
        // systemFlag: data.systemFlag
      }
      this.editId = data.id
    },
    // 主表选择
    handleClick(data) {
      this.id = data.id
      this.type = data.type
      // this.systemFlag = data.systemFlag
      // this.subRequestParams.column.push({
      //   value: 'parentId'
      // })
      // this.subRequestParams.column.push({
      //   key: 'grade',
      //   value: 2
      // })
    },
    //右边表格顶部的按钮事件
    handleSubOperateEvent(data) {
      if (this.type == '') {
        this.$message.error('未选择订单类型')
        return
      }
      // if (this.systemFlag == '1') {
      //   this.$message.info(this.$t('dict.noEditMessage'))
      //   return
      // }
      this.title = '新增'
      this.tableChange = 'right'
      this.formDataDialog = {}
      this.visibleSub = true
    },
    //右边行操作事件
    rightRowOperate({ handleName, row }) {
      const fun = {
        editSub: () => {
          // if (this.systemFlag == '1') {
          //   this.$message.info(this.$t('dict.noEditMessage'))
          //   return
          // }
          this.title = '编辑'
          this.tableChange = 'right'
          this.editSub(row)
          this.visibleSub = true
        },
        deleteSub: () => {
          // if (this.systemFlag == '1') {
          //   this.$message.info(this.$t('dict.noEditMessage'))
          //   return
          // }
          this.$confirm(
            "此操作将删除该数据及关联明细数据, 是否继续?",
            this.$i18n.t('common.tip'),
            {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
            .then(() => {
              typeOrderDeleteById(row.id).then((res) => {
                this.$message({
                  type: 'success',
                  message: '删除成功'
                })
                this.$refs.table.subRefresh(true)
              })
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: this.$i18n.t('common.cancel')
              })
            })
        },
        // 如果当前项是默认值，将其切换为非默认；如果不是，切换为默认，且其他选项设置为非默认
        defaultConfig: () => {
          let param = {
            dictId: row.dictId,
            id: row.id,
            isDefault: row.isDefault
          }
          setDictItemDefault(param).then((res) => {
            this.$refs.table.subRefresh(true)
            this.visibleSub = false
          })
        }
      }
      fun[handleName] && fun[handleName]()
    },
    editSub(data) {
      this.formDataDialog = {
        ...data,
        recheckDicId: data.recheckDicId.split(',')
      }
      this.editId = data.id
    },
    handleSubmit(data) {
      if (this.title == '新增' && this.tableChange == 'left') {
        typeOrderCreate({
          ...data,
          grade: 1
        }).then((res) => {
          this.$refs.table.refresh(true)
          this.visible = false
        })
      } else if (this.title == '编辑' && this.tableChange == 'left') {
        typeOrderUpdate({
          ...data,
          id: this.editId
        }).then((res) => {
          this.$refs.table.refresh(true)
          this.visible = false
        })
      }
    },
    handleSubmitSub(data) {
      if (this.title == '新增' && this.tableChange == 'right') {
        typeOrderCreate({
          ...data,
          grade: 2,
          parentId: this.id,
          recheckDicId: data.recheckDicId.join(',')
        }).then((res) => {
          this.$refs.table.subRefresh(true)
          this.visibleSub = false
        })
      } else if (this.title == '编辑' && this.tableChange == 'right') {
        typeOrderUpdate({
          ...data,
          grade: 2,
          parentId: this.id,
          recheckDicId: data.recheckDicId.join(',')
        }).then((res) => {
          this.$refs.table.subRefresh(true)
          this.visibleSub = false
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
// .dict {
//   /deep/.master-sub-page {
//     display: flex;
//     // justify-content: space-between;
//     align-items: flex-end;
//   }
//   /deep/.el-table {
//     height: 445px !important;
//   }
//   /deep/.main {
//     margin-right: 50px;
//     width: 50%;
//   }
//   /deep/.subTable{
//     width: 45%;
//   }
// }
</style>
